import 'dart:async';
import 'dart:convert';

import 'package:detect/entity/entity.dart';
import 'package:detect/notifier/fpga_time.dart';
import 'package:detect/notifier/state.dart';
import 'package:detect/utils/api_util.dart';
import 'package:detect/utils/db_util.dart';
import 'package:detect/utils/ws_util.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ChatNotifier extends ChangeNotifier {
  late final BuildContext context;

  void init(final BuildContext context) {
    this.context = context;
    WSUtil.connect().listener([
      ReceiveMsgListener("text", (response) {
        try {
          Map<String, dynamic> msg = jsonDecode(response['msg']);
          int? senderId = msg['senderId'], receiverId = msg['receiverId'];
          if (senderId != null && receiverId != null && senderId != receiverId && receiverId == context.read<StateNotifier>().localId) {
            String time = this.context.read<FpgaTimeNotifier>().format("yyyy-MM-dd HH:mm:ss");
            DBApi.chat.insert(ChatEntity(senderId, receiverId, msg['content'], 0, time)).then((value) {
              if (value != null) notifyListeners();
            });
          }
        } catch (e) {
          ///TODO
        }
        return false;
      }),
    ]);
  }

  Future<void> sendText(int receiverId, String content) {
    int? senderId = context.read<StateNotifier>().localId;
    if (senderId != null) {
      Completer<void> completer = Completer();
      content = content.trim();
      ApiUtil().sendText(jsonEncode({"senderId": senderId, "receiverId": receiverId, "content": content})).then((value) {
        String time = context.read<FpgaTimeNotifier>().format("yyyy-MM-dd HH:mm:ss");
        DBApi.chat.insert(ChatEntity(senderId, receiverId, content, 0, time)).then((value) {
          if (value != null) {
            notifyListeners();
            completer.complete();
          }
        });
      });
      return completer.future;
    } else {
      return Future.value();
    }
  }
}
